$(function () {
  collection = 1;
  initCollectionData();
  initCollectionTable();

});

//chart界面数据初始化
function initCollectionData() {
  var data;
  $.ajax({
    url: `${URL}clickhouse/receive/chart`,
    async: false,
    success: function (res) {
      if (res.code == 200) {
        data = res.data
      }
    },
  })
  console.log(data, '项目收款（chart）数据')
  CollectionData(data);
  return data;
}
//项目收款（chart）数据
function CollectionData(data) {
  let xAxis = [];
  data.xAxis.forEach((item) => {
    xAxis.push(item.value);
  })
  let legendata = [];
  data.series.forEach((item) => {
    legendata.push(item.name);
  })
  let xData = xAxis
  let legendData = legendata;
  // let Data = [{
  //   name: 'A',
  //   type: 'bar',
  //   barWidth: '25',
  //   barGap: 0,
  //   itemStyle: {
  //     color: '#165DFF'
  //   },
  //   data: [125, 34, 55, 66, 2, 334, 556, 34, 677, 85, 964, 753]
  // },
  // {
  //   name: 'B',
  //   type: 'bar',
  //   barWidth: '25',
  //   barGap: 0,
  //   itemStyle: {
  //     color: '#0AA5A8'
  //   },
  //   data: [12, 34, 550, 466, 2, 334, 556, 34, 677, 85, 864, 753]
  // },
  // {
  //   name: 'C',
  //   type: 'bar',
  //   barWidth: '25',
  //   barGap: 0,
  //   itemStyle: {
  //     color: '#50CD89'
  //   },
  //   data: [12, 334, 255, 566, 2, 334, 556, 34, 677, 85, 564, 753]
  // },
  // ]
  let histogramLegendData = [];
  let Data = [];
  for (var i = 0; i < data.series.length; i++) {
    histogramLegendData.push(data.series[i].name); // 项目
    var nums = [];
    for (var j = 0; j < data.series[i].yAxis.length; j++) {
      nums.push(data.series[i].yAxis[j].value);
    }
    Data.push({
      name: data.series[i].name,
      type: "bar",
      barGap: 0,
      barWidth: '35',
      barGap: 0,
      //   barWidth: "18px",
      //   itemStyle: {
      //     normal: {
      //       color: awardColor[i],
      //     },
      //   },
      data: nums,
      label: {
        normal: {
          show: true,
          fontSize: 12,
          color: "#393F4F",
          position: "top",
          formatter: "{c}",
        },
      },
    });
  }
  have('collChart') ? yueduqushi('collChart', xData, legendData, Data) : ''
}
//table界面数据初始化
let data;//表格数据
function initCollectionTable() {
  $.ajax({
    url: 'http://www.esunrising.net:8087/clickhouse/receive/all',
    async: false,
    success: function (res) {
      if (res.code == 200) {
        data = res.data
      }
    },
  })
  console.log(data, '项目收款（table）数据')
  let tr = '';
  //渲染table_coll表格数据
  for (let i = 0; i < data.length; i++) {
    tr += `<tr>  <td id="order">${data[i].id}</td> <td  id="year">${data[i]['year']}</td> <td id="project">${data[i]['project']}</td> <td id="receiveMoney">${data[i]['receiveMoney']}</td> <td id="claimMoney">${data[i]['claimMoney']}</td> <td id="invoiceMoney">${data[i]['invoiceMoney']}</td> <td> <a href="#" style="cursor: pointer; color: #00B42A; display:none" onclick="saveAll(this)" id="save_btn"  >保存</a> <a href="#" style="cursor: pointer; color: #00B42A;" onclick="edit(this)" id="edit_btn">编辑</a> &nbsp;<a href="#" style="cursor: pointer;  color: #F53F3F;" onclick="del(this)" id="del">删除</a></td> </tr>`
    $('#table_coll').html(tr);
  }
  return data;
}
//搜索
function OnSearchBtnClicked() {
  console.log(data, "shuju")
  let searchInput = document.getElementById('search');
  let searchValue = searchInput.value;
  console.log(searchValue, "搜索内容")
  let tr = '';

  $.ajax({
    url: 'http://www.esunrising.net:8087/clickhouse/receive/all',
    async: false,
    data: {
      param: searchValue,
    },
    success: function (res) {
      if (res.code == 200) {
        if (res.data.length > 0) {
          data = res.data;
          //渲染table_coll表格数据
          for (let i = 0; i < data.length; i++) {
            tr += `<tr>  <td id="order">${data[i].id}</td> <td  id="year">${data[i]['year']}</td> <td id="project">${data[i]['project']}</td> <td id="receiveMoney">${data[i]['receiveMoney']}</td> <td id="claimMoney">${data[i]['claimMoney']}</td> <td id="invoiceMoney">${data[i]['invoiceMoney']}</td> <td> <a href="#" style="cursor: pointer; color: #00B42A; display:none" onclick="saveAll(this)" id="save_btn"  >保存</a> <a href="#" style="cursor: pointer; color: #00B42A;" onclick="edit(this)" id="edit_btn">编辑</a> &nbsp;<a href="#" style="cursor: pointer;  color: #F53F3F;" onclick="del(this)" id="del">删除</a></td> </tr>`
            $('#table_coll').html(tr);
          }
        } else {
          tr += '';
          $('#table_coll').html(tr);

          // 没有匹配到数据提示
          prompt('没有匹配到数据', '.alert-info', 4000);

          // alert('没有匹配到数据')
        }

      }
    },
  })
  console.log(data, '搜索内容数据')

  return data;
}

//获取键盘的按键
$(search).keyup(function (event) {
  if (event.keyCode == 13) {
    // $(“input[name=‘SerchBtn’]”).trigger(“click”);
    //调用搜索方法
    OnSearchBtnClicked();
  }
});


//遮罩层点击确认
function confirm() {
  let ta = document.getElementById('scheduletable');
  let tr = ta.insertRow(1);
  let cell0 = tr.insertCell(0);
  let cell1 = tr.insertCell(1);
  let cell2 = tr.insertCell(2);
  let cell3 = tr.insertCell(3);
  let cell4 = tr.insertCell(4);
  let cell5 = tr.insertCell(5);
  let cell6 = tr.insertCell(6);
  let Addarr = []
  let Addobj = {
    "project": document.getElementById('zcellproject').value,
    "year": document.getElementById('zyear').value,
    "receiveMoney": document.getElementById('zreceiveMoney').value,
    "claimMoney": document.getElementById('zclaimMoney').value,
    "invoiceMoney": document.getElementById('zinvoiceMoney').value,
  }
  Addarr.push(Addobj);
  console.log(Addarr, "Addarr")
  if (document.getElementById('zcellproject').value) {
    //点击确认 往表格里追加
    $.ajax({
      url: 'http://www.esunrising.net:8087/clickhouse/receive/save',
      async: false,
      method: 'post',
      contentType: 'application/json;charset=UTF-8', //contentType很重要 
      data: JSON.stringify(Addarr),
      success: function (res) {
        if (res.code == 200) {
          // cell0.innerHTML = document.getElementById('zorder').value
          cell1.innerHTML = document.getElementById('zyear').value
          cell2.innerHTML = document.getElementById('zcellproject').value
          cell3.innerHTML = document.getElementById('zreceiveMoney').value
          cell4.innerHTML = document.getElementById('zclaimMoney').value
          cell5.innerHTML = document.getElementById('zinvoiceMoney').value
          cell6.innerHTML = " <a href='#' style='cursor: pointer; color: #00B42A;' onclick='edit(this)' >编辑</a> &nbsp;<a href='#' style='cursor: pointer;  color: #F53F3F;' onclick='del(this)' id='del'>删除</a>"

          //关闭遮罩层
          document.getElementById('light').style.display = 'none';
          document.getElementById('fade').style.display = 'none';
          //
          initCollectionData();
          initCollectionTable();
          //数据新增成功提示
          prompt(res.msg, '.alert-info', 1000);


        } else {
          prompt('输入框不能为空', '.alert-info', 1000);
        }
      },
    })

  } else {
    prompt('输入框不能为空', '.alert-info', 1000);
  }




}
//新增
function add() {
  //把输入框内容置空
  document.getElementById('zyear').value = ''
  document.getElementById('zcellproject').value = ''
  document.getElementById('zreceiveMoney').value = ''
  document.getElementById('zclaimMoney').value = ''
  document.getElementById('zinvoiceMoney').value = '';

  document.getElementById('light').style.display = 'block';
  document.getElementById('fade').style.display = 'block'
}

//编辑
function edit(item) {
  let tr = item.parentNode.parentNode
  $("#edit_btn", tr).hide();
  $("#save_btn", tr).show();

  // console.log(tr.children[0], "cccc")

  // let cell0 = tr.cells[0];
  let cell1 = tr.cells[1];
  let cell2 = tr.cells[2];
  let cell3 = tr.cells[3];
  let cell4 = tr.cells[4];
  let cell5 = tr.cells[5];

  // cell0.innerHTML = "<input type='text'  value=' " + cell0.innerHTML + "' placeholder='输入序号'  class='input' onchange='change(this)' ></input>"
  cell1.innerHTML = "<input type='text'  value=' " + cell1.innerHTML + "' placeholder='输入年份'  class='input' id='inp_year'></input>"
  cell2.innerHTML = "<input type='text'  value=' " + cell2.innerHTML + "' placeholder='输入项目名称'  class='input'id='inp_pro'></input>"
  cell3.innerHTML = "<input type='text'  value=' " + cell3.innerHTML + "' placeholder='到款金额'  class='input' id='inp_rec'></input>"
  cell4.innerHTML = "<input type='text'  value=' " + cell4.innerHTML + "' placeholder='输入认领金额'  class='input' id='inp_cla'></input>"
  cell5.innerHTML = "<input type='text'  value=' " + cell5.innerHTML + "' placeholder='输入开票金额'  class='input' id='inp_inv'></input>"

  // console.log(document.getElementsByClassName("input")[0].value, "order")

}
//保存
function saveAll(item) {
  let thistr = item.parentNode.parentNode;//获取该行节点
  let savearr = []
  let saveobj = {
    "project": document.getElementById("inp_pro", thistr).value,
    "year": document.getElementById("inp_year", thistr).value,
    "receiveMoney": document.getElementById("inp_rec", thistr).value,
    "claimMoney": document.getElementById("inp_cla", thistr).value,
    "invoiceMoney": document.getElementById("inp_inv", thistr).value,
  }
  savearr.push(saveobj);
  console.log(savearr, "savearr")
  //点击保存 数据更新
  $.ajax({
    url: 'http://www.esunrising.net:8087/clickhouse/receive/update',
    async: false,
    method: 'post',
    contentType: 'application/json;charset=UTF-8',
    data: JSON.stringify(savearr),
    success: function (res) {
      if (res.code == 200) {
        thistr.children[1].innerHTML = document.getElementById("inp_year", thistr).value;
        thistr.children[2].innerHTML = document.getElementById("inp_pro", thistr).value;
        thistr.children[3].innerHTML = document.getElementById("inp_rec", thistr).value;
        thistr.children[4].innerHTML = document.getElementById("inp_cla", thistr).value;
        thistr.children[5].innerHTML = document.getElementById("inp_inv", thistr).value;
        $("#edit_btn").show();
        $("#save_btn").hide();
        prompt(res.msg, '.alert-info', 1000);

      }
    },
  })




}




//删除
function del(item) {
  let table = item.parentNode.parentNode.parentNode;
  let tr = item.parentNode.parentNode;

  let idstr = tr.children[0].innerHTML
  let idobj = { "idStr": idstr }
  let data;
  $.ajax({
    url: 'http://www.esunrising.net:8087/clickhouse/receive/delete',
    method: 'post',
    async: false,
    contentType: 'application/json;charset=UTF-8',
    data: JSON.stringify(idobj),
    success: function (res) {
      console.log(res, "res")
      if (res.code == 200) {
        // "数据删除成功"提示
        prompt(res.msg, '.alert-info', 1000);
        table.removeChild(tr);
        initCollectionData();
        initCollectionTable();

      }
    },
  })
  console.log(data)

}

//自定义弹出框
var prompt = function (message, style, time) {
  style = (style === undefined) ? '.alert-info' : style;
  time = (time === undefined) ? 1200 : time;
  $('<div id="promptModal">')
    .appendTo('body')
    .addClass('alert ' + style)
    .css({
      "color": "#fff",
      "background-color": "gray",
      "opacity": "0.8",
      "border-color": "#d6e9c6",
      "display": "block",
      "z-index": 99999,
      "left": ($(document.body).outerWidth(true) - 120) / 2,
      "top": ($(window).height() - 45) / 2,
      "position": "absolute",
      "padding": "24px",
      "border-radius": "5px"
    })
    .html(message)
    .show()
    .delay(time)
    .fadeOut(10, function () {
      $('#promptModal').remove();
    });
};

